<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { reqGetStatistics3 } from '../api/index'
import { useResizeObserver } from '@vueuse/core'

const current = ref('week')
const options = [
  {
    text: '近一月',
    value: 'month'
  },
  {
    text: '近一周',
    value: 'week'
  },
  {
    text: '近24小时',
    value: 'hour'
  }
]
function handleChoose(val: string) {
  current.value = val
  getData()
}

let myChart = null
onMounted(() => {
  const chartDom = document.getElementById('chart')
  if (chartDom) {
    myChart = echarts.init(chartDom)
    getData()
  }
})
function getData() {
  const option = {
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'bar'
      }
    ]
  }
  // @ts-expect-error myChart 类型为 any
  myChart.showLoading() // 显示加载动画loading
  reqGetStatistics3({ type: current.value })
    .then((res) => {
      if (res.msg === 'ok') {
        option.xAxis.data = res.data.x
        option.series[0].data = res.data.y
        // @ts-expect-error myChart 类型为 any
        myChart.setOption(option)
      }
    })
    .finally(() => {
      // @ts-expect-error myChart 类型为 any
      myChart.hideLoading()
    })
}
// 监听窗口大小变化 并重新渲染图表
const el = ref(null)
useResizeObserver(el, () => {
  // console.log(entries)
  // @ts-expect-error myChart 类型为 any
  if (myChart) myChart.resize()
})
// 打包后容易白屏 销毁图表
onBeforeUnmount(() => {
  if (myChart) echarts.dispose(myChart)
})
</script>

<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>订单统计</span>
          <div>
            <el-check-tag
              :checked="current == item.value"
              style="margin-right: 8px"
              v-for="(item, index) in options"
              :key="index"
              @click="handleChoose(item.value)"
              >{{ item.text }}</el-check-tag
            >
          </div>
        </div>
      </template>
      <div ref="el" id="chart" style="width: 100%; height: 310px"></div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
